﻿using UnityEngine;

public class LoadingMgr : Singleton<LoadingMgr>
{
    private int rate;
    private string progress;
    private LoadingPanel view;

    public LoadingMgr()
    {
        Transform trans = AllUpdate.GetChildByName("Loading");
        view = new LoadingPanel(trans.gameObject);
        progress = view.Load_txt.text;
    }

    public void Open()
    {
        // 保证每次调用都会顺利打开，否则会出现图集丢失的问题
        Utility.SetActive(view.Go, false);
        ZEventCenter.RemoveEventListener(ConstData.PROGRESS_UPDATE, OnProgress);

        if (view != null && !view.Go.activeInHierarchy)
        {
            Utility.SetActive(view.Go, true);
            ZEventCenter.AddEventListener(ConstData.PROGRESS_UPDATE, OnProgress);
        }
    }

    public void Close()
    {
        if (view != null)
        {
            Utility.SetActive(view.Go, false);
            ZEventCenter.RemoveEventListener(ConstData.PROGRESS_UPDATE, OnProgress);
        }
    }

    private void OnProgress(ZEvent ev)
    {
        rate = (ev as LoadEvent).rate;
        ShowProgress();
    }

    private void ShowProgress()
    {
        view.Load_sdr.value = rate * 0.01f;
        view.Load_txt.text = string.Format(progress, rate * 0.01f);
    }
}